<?php 
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions  
  http://www.oscommerce.com

  Copyright (c) 2010 osCommerce

  Released under the GNU General Public License
*/	  
  	
  require('includes/application_top.php');


  if (!isset($_FILES['fileUpload']))
    { tep_redirect(tep_href_link(FILENAME_AUTO_IMPORT, '')); }
  else
     if (!isset($_FILES['fileUpload']['name']))
            { tep_redirect(tep_href_link(FILENAME_AUTO_IMPORT, '')); }
			 
  require(DIR_WS_CLASSES . 'currencies.php');
  
  $upload = new upload('fileUpload');
  $upload->set_destination(DIR_FS_CATALOG.'admin/uploads/input_data/'); // mandatory
  $upload->set_permissions('777'); // optional
  $upload->set_extensions('csv'); // optional
  // echo DIR_FS_CATALOG.'admin/uploads/input_data/'."<br>";
 
  if ($upload->parse() && $upload->save()) {
    $msg = 'File ' . $upload->filename . ' has been uploaded successfully.';
  } else {
     $msg = 'Error processing ' . $upload->filename . '.';	
	  
	 tep_redirect(tep_href_link(FILENAME_AUTO_IMPORT, '')); 
  }
  // tep_redirect(tep_href_link(FILENAME_CATEGORIES, 'cPath=' . $cPath));
 $tbl ='<table id="my_datatable1" class="display">
    <thead>
        <tr>
            <th>ASIN</th>
			<th>TITLE</th>
            <th>DATE AVAILABLE</th>
            <th>PRICE</th>
            <th>STATUS</th>
			<th>MANUFACTURER</th>	
			<th>MODEL</th>
			<th>WEIGHT</th>
			<th>DIMENSIONS</th>
			<th>STOCK</th>
			<th>VIDEO</th>
        </tr>
    </thead>
    <tbody>';  
  
  $currencies = new currencies();

  $action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : 'insert_product');
  
  $products_id = 0;

  set_time_limit(0);
  
  $name = DIR_FS_CATALOG.'admin/uploads/input_data/'.$upload->filename;
  
  $row  = 1;

  $c = str_replace("[:|:]", "|", file_get_contents($name));//"\t"

  file_put_contents('import.tmp',$c); 
				
  $handle = fopen('import.tmp', "r"); 
			
  $parent      = array(); 
  $category_id = array();
  $cat_id      = array();									
  $inner_cat   = array();									
  $cat		   = array();
  $inner_Path  = array();
  $path  = array();
	
  while (($data = fgetcsv($handle, 0, "|")) !== FALSE) { 
 				  
  $num = count($data);        						                				
			
 if ($row > 1)
	  {					 	  
	     $tbl.= '<tr>';
		        					   					   					  					  								
			 	$date_avail = $data[0]; //date('Y-m-d'); 0. DATE AVAILABLE
				$date_avail = (date('Y-m-d') < $date_avail) ? $date_avail : 'null';	
				
				$p_realstatus = 0;			
				
				$asin    	= $data[1];	//1. ASIN			
				//echo "ASIN = ".$asin."<br>";
				$price    	= $data[2]; //2.PRICE	
				
				$prime    	= trim($data[3]); //3.PRIME				
				
				//echo "prime = $prime <br>";
				
				$status 	= trim($data[4]); //4.STATUS							
				
				$manufac    = trim($data[5]); //5.MANUFACTURER	
				
				$manu_id 	= get_manu_id($manufac); 
				
				if ($manu_id == 0)
				   {
					  $manu_id = new_manu_id($manufac); 
				   }
										 			
				$model    	= trim($data[6]); //6.MODEL					
				
				if ($model=='N/A') $model = '';
				
			//	echo "model = $model <br>";
				
				$title     	= trim($data[7]); //7.TITLE 
     		    
				//$title      = convert_title_url($title);
																
                $desc		= standard_content(trim($data[9])); //9.DESCRIPTION	 								 				
												
			    //echo $desc; die('=======================');
				
				$details    = standard_content(trim($data[8])); //8.DETAILS	 
				
				//echo "Desc = ".$desc."<br>";								
				
				//echo "Detail = ".$details."<br>";
				
			 /*   $div_begin = substr_count($desc, '<div'); 
				
				$div_end = substr_count($desc, '</div>'); 				*/
				
				$weight		= (float)($data[10]); //10.SHIPPING WEIGHT	
				
			//	echo "weight = $weight"."<br>";
				
				$dimensions = $data[11]; //11.DIMENSIONS		
				
				//echo "dimensions = ".$dimensions."<br>";
				
				$stock 		= (int)($data[12]); //12.stock		
				
				$url_amazon = trim($data[13]); //13.amazon url			
				
				//echo "url_amazon = $url_amazon <br>";
				
				$also_bought  = explode("||", $data[14]);  //14 = ALSO BOUGHT
				
				//echo "also_bought = ".$data[14]."<br>";
				
				$videos = trim($data[15]); //15.VIDEO					
				
				//echo 	" videos = $videos <br>";
					  
				$ratings = $data[16]; //16.AVERAGE RATING	
							
				$reviews_count=	 (int)($data[17]);//17.REVIEWS COUNT	
				
				$tbl.= '<td>'.$asin.'</td>'; 
				$tbl.= '<td>'.$title.'</td>';
				$tbl.= '<td>'.$date_avail.'</td>'; 
				$tbl.= '<td>'.$price.'</td>';
				$tbl.= '<td>'.$status.'</td>'; 
				$tbl.= '<td>'.$manufac.'</td>';
				$tbl.= '<td>'.$model.'</td>'; 
				$tbl.= '<td>'.$weight.'</td>';
				$tbl.= '<td>'.$dimensions.'</td>';
				$tbl.= '<td>'.$stock .'</td>'; 
				$tbl.= '<td>'.$videos.'</td>';
			
				$pos = strpos($status, 'In Stock');
				if ($pos === false) {  $p_realstatus =0; } else $p_realstatus =1;										    																	
				$review_rate  = explode("||", $data[18]);  //18 = REVIEW RATING
				$review_title = explode("||", $data[19]); //19 = REVIEW TITLE
				$review_date  = explode("||", $data[20]);  //20 = REVIEW DATE
   
				$review_content = explode("||", $data[21]); //REVIEW CONTENT								
				
				$s_image = explode("||", $data[22]);  //22 = S. IMAGES
				
				$m_image = explode("||", $data[23]); //23 = M. IMAGES
				$l_image = explode("||", $data[24]);  //24 = L. IMAGES									
				
				//echo "M.Images : ".$data[23]."<br>"; print_r($m_image); echo "<br>";
				
				//echo "S.Images : ".$data[22]."<br>"; print_r($s_image); echo "<br>";
				//echo "L.Images : ".$data[24]."<br>"; print_r($l_image); echo "<br>";
				
				$english_id     = 1;//current language
				
				//echo "+++++++++++++++++++++++++++++++++++++++++<br>";
				//--------------------Category ---------------------------------
					
				$categories   	= trim($data[25]);	//25.CATEGORY	   
				$inner_categories = trim($data[26]);	//26.INNER CATEGORY	
				
				$cat = explode(">", $categories);	
				
				if (is_array($cat)&&(count($cat)>0)) $category = trim($cat[count($cat)-1]);
				
				if 	($inner_categories!='')	
				{	
					$inner_cat = explode(">", $inner_categories );	
					
					if (is_array($inner_cat)&&(count($inner_cat)>0)) 
					$inner_category = trim($inner_cat[count($inner_cat)-1]);				
				}
				
				//echo "<b>Category</b> = $categories<br>";
				//echo "<b>Iner Category</b> = $inner_categories <br>";
				
				//  Category = Electronics > Computers & Accessories > Tablets
				//	Iner Category = Electronics > Computers & Add-Ons > Tablets 
				$category_id[0] = 0;
				
				for ($k=0;$k<count($cat);$k++)
				  {  
				     $cat[$k]  = trim($cat[$k]);
					 //---Kiem tra xem da ton tai category name chua co the co nhieu cat trung ten

					 if ($k==0) { $parent[0] = 0; $path[0] = $cat[0]; }
					 else 
					    { $parent[$k] = $category_id[$k-1];  $path[$k] = $path[$k-1].' > '.$cat[$k]; }
					
					  //---Kiem tra xem da ton tai category name chua ?
					 $category_id[$k] = get_category_id($cat[$k],1,$path[$k]);
					 								  
					 if ( $category_id[$k] == 0 ) // chua co trong database
					    {
						   $category_id[$k] = new_category($parent[$k],$cat[$k],$path[$k]);
					    }
					/* else //------Da co trong database,kiem tra father_id cua no
					    {
							$father_id = get_father_cat($category_id[$k]);
							
							if ( $father_id !=  $parent[$k] )
							    {
									$category_id[$k] = new_category($parent[$k],$cat[$k],$path[$k]);
								}
						} */
				  }								
					 
			if ($k>0) { $cat1_id = $category_id[$k-1];	} else { $cat1_id = 0; }
								
			$cat2_id   = 0; 
			$cat_id[0] = 0;
			
			if 	($inner_categories!='')	
			  {	
					  
				for ($k=0;$k<count($inner_cat);$k++)
				  {  				  
				     $cat[$k] = trim($inner_cat[$k]);
															 
					 if ($k==0) { $parent[0] = 0; $inner_Path[$k] = $cat[$k]; }
					 else 
					    { $parent[$k] = $cat_id[$k-1];  $inner_Path[$k] = $inner_Path[$k-1].' > '.$cat[$k]; }
					
					  //---Kiem tra xem da ton tai category name chua ?
					 $cat_id[$k] = get_category_id($inner_cat[$k],1,$inner_Path[$k]);
					  
					 if ( $cat_id[$k] == 0 ) //chua co trong database
					   {
						   $cat_id[$k] = new_category($parent[$k],$inner_cat[$k],$inner_Path[$k]);
					   }
					/* else //------Da co kiem tra father_id cua no
					    {							 
						   $father_id = get_father_cat($cat_id[$k]);
							
						   if ( $father_id !=  $parent[$k] )
							    {
									$cat_id[$k] = new_category($parent[$k],$inner_cat[$k]);
								}
						   else //-------- Kiem tra tiep ------------
							    {															 
									$grandfather_id = get_father_cat($father_id);
									
									if ($k>0)
									 if ( ($grandfather_id>0) && ($parent[$k-1]!=$grandfather_id))
									   {
										  $cat_id[$k] = new_category($parent[$k],$inner_cat[$k]); 
									   }
								}
						}					*/						
				 }
				  
				  if ($k>0) { $cat2_id = $cat_id[$k-1]; } else { $cat2_id = 0; }					   							
			}


 $action == 'insert_product';
 $products_status = 1;// show in front end
 
 if (strtolower($prime)=='yes') { $pri = 1; } else { $pri = 0; }
 
 $sql_data_array = array('products_ship_sep' =>(isset($products_ship_sep)? '1':'0'),                         
						 'ASIN' => tep_db_prepare_input($asin),
						 'amazon_url' => tep_db_prepare_input($url_amazon),
						 'products_quantity' => $stock,						 
                         'products_model' => tep_db_prepare_input($model),
						 'products_image' => tep_db_prepare_input($m_image[0]),
                         'products_date_added' => date('Y-m-d'),
                         'products_price' => tep_db_prepare_input($price),
                         'products_date_available' => $date_avail,
                         'products_weight' => (float)tep_db_prepare_input($weight),
                         'products_rating' => (float)tep_db_prepare_input($ratings),
                         'products_review_count' => $reviews_count,
                         'products_status' => $products_status,
                    //   'products_tax_class_id' => tep_db_prepare_input($HTTP_POST_VARS['products_tax_class_id']),
                       	  'manufacturers_id' => $manu_id,
					      'also_bought' => tep_db_prepare_input($data[14]),
						  'prime' => $pri,
		);

  //  $sql_data_array['products_image'] = tep_db_prepare_input($products_image->filename);

 $check_asin_product_id = check_asin($asin);
 
// echo "Asin = $asin <br>"; 
 //echo "<br>====================<br>";
 
 if ( $check_asin_product_id==0 )
 if ($action == 'insert_product') {
          		  
		  $insert_sql_data = array('products_date_added' => date('Y-m-d'));

          $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

          tep_db_perform(TABLE_PRODUCTS, $sql_data_array);
          
		  $products_id = tep_db_insert_id();
          
		  //-----Kiem tra da ton tai hay chua?---------
		//  echo "Check $cat1_id | $products_id = ".check_cat($cat1_id,$products_id)."<br>";
		  
		 if (!check_cat($cat1_id,$products_id) && ($cat1_id>0))   
          tep_db_query("insert into " . TABLE_PRODUCTS_TO_CATEGORIES . " (products_id, categories_id) values (" . (int)$products_id . "," . (int)($cat1_id) . ")");
 				
		  if (!check_cat($cat2_id,$products_id) && ($cat2_id>0)) 
		    tep_db_query("insert into " . TABLE_PRODUCTS_TO_CATEGORIES . " (products_id, categories_id) values (" . (int)$products_id . "," . (int)($cat2_id) . ")");		  		  		  		    			

		  $languages = tep_get_languages();
								
		  for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
				  $language_id = $languages[$i]['id'];
		
				  $sql_data_array = array('products_name' => tep_db_prepare_input($title),
					 'products_description' => tep_db_prepare_input($desc),
					 'products_specifications' => tep_db_prepare_input($details),
					 'products_experience' => '',
					 'products_status' => $status // In Stock | Out of Stock 
					 );
		
				  if ($action == 'insert_product') {
					$insert_sql_data = array('products_id' => $products_id,
											 'language_id' => $language_id);
		
					$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
		
					tep_db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array);
				  } 
				  /*elseif ($action == 'update_product') {
					tep_db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array, 'update', "products_id = '" . (int)$products_id . "' and language_id = '" . (int)$language_id . "'");
				  }*/
				}						
				 
			for ($k=0;$k<count($m_image);$k++)
				 {  
					   if (!isset($s_image[$k])) $s_image[$k]='';
					   if (!isset($m_image[$k])) $m_image[$k]='';
					   if (!isset($l_image[$k])) $l_image[$k]='';

				tep_db_query("insert into " . TABLE_PRODUCTS_IMAGES . " (products_id, image,sort_order,s_image,l_image) values ('" . (int)$products_id . "','" . tep_db_input($m_image[$k]) . "',".$k.",'" . tep_db_input($s_image[$k]) . "','" . tep_db_input($l_image[$k]) . "')");	
				 		
				}	
				
  //------------------------------ Product's Videos ------------------------------------------				

 if (!check_video($video,$products_id))
tep_db_query("insert into " .  TABLE_PRODUCTS_VIDEOS . " (products_id, video) values (" . $products_id . ",'".$videos."')");
  				
 //-------------------------------------------------------------------------------------------
     for ($i=0;$i<count($review_rate);$i++)
			{				
			    $t = strtotime($review_date[$i]);
				 	
				tep_db_query("insert into " .  TABLE_REVIEWS . " (products_id, customers_id,reviews_rating,date_added,reviews_status,reviews_read) values (" . $products_id . ",0,".$review_rate[$i].",'".date('Y-m-d',$t)."',1,0)");	
				
				$review_id = tep_db_insert_id();
			
				$review_title[$i]   = tep_db_prepare_input($review_title[$i]);
				
				$review_content[$i] = tep_db_prepare_input($review_content[$i]);
	
	//tep_db_input() : goi sau khi da luu vao database,		 tep_db_prepare_input	
									
		  for ($ii=0, $n=sizeof($languages); $ii<$n; $ii++) {
				  
				  $language_id = $languages[$ii]['id'];
				  	
				tep_db_query("insert into " .  TABLE_REVIEWS_DESCRIPTION  . " (reviews_id, languages_id,reviews_text,review_title) values (" . (int)$review_id  . ",". $language_id.",'".tep_db_input($review_content[$i])."',". "'".tep_db_input($review_title[$i])."')");
				
		       }
			   
			}							
				
        } /*elseif ($action == 'update_product') {
			
          $update_sql_data = array('products_last_modified' => 'now()');

          $sql_data_array = array_merge($sql_data_array, $update_sql_data);

          tep_db_perform(TABLE_PRODUCTS, $sql_data_array, 'update', "products_id = '" . (int)$products_id . "'");
        }*/        
				  //--------------REVIEWS ----------------------------------------------------------------						   	    
				  
				  $tbl.= '</tr>';													
	  }

		$row++;		  
  }

  $tbl.= '</tbody></table>';
  
fclose($handle); 

unlink('import.tmp'); 	

//---------------------------------------------------------------------------------------------------------

function standard_content($desc)
{
 $desc = trim($desc);
 $pos  = strpos($desc, "</a>");

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) { }
else
{
   $p1 = $pos+strlen("</a>");
  
   $st = ''.substr($desc, 0, $pos );     
   //------Kiem tra xem co <a ko? -----
   $p2  = strpos($st, "<a href");
   
   if ($p2===false) { $desc  = substr($desc,$p1,strlen($desc)-$p1);   }
}
			  
  $a_begin = substr_count($desc, '<a href'); 
				
  $a_end = substr_count($desc, '</a>'); 
	
	if  ($a_begin > $a_end)
	  {
		   for ($i=$a_end;$i < $a_begin;$i++)  $desc = $desc."</a>";
	  }			  	 
  
  $div_begin = substr_count($desc, '<div'); 
				
	$div_end = substr_count($desc, '</div>'); 
	
	if  ($div_begin > $div_end)
	  {
		   for ($i=$div_end;$i < $div_begin;$i++)  $desc = $desc."</div>";
	  }	
	  	
  $desc = str_replace('class=content"','class=content123',$desc);
  $order   = array('ï','¿','½','�');
  $replace = '';

  return str_replace($order, $replace, $desc); 
}

function convert_title_url($s)
{

  $order   = array("(", ")", "\t",",",";","%","+");
  $replace = '-';

  return str_replace($order, $replace, $s);
}

function check_asin($asin)
{
 if ($asin=='' || empty($asin)) { return -1; }

 $qq = tep_db_query("select products_id from ".TABLE_PRODUCTS." where ASIN = '".tep_db_prepare_input($asin)."'");
				
 $ff = tep_db_fetch_array($qq);	

 if (is_array($ff)) { return $ff['products_id']; } else { return 0; }
}

function check_cat($cat_id,$products_id)
{
 if ( $cat_id == 0 ) return false;
 
 $q = tep_db_query("select products_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " where categories_id = $cat_id  and products_id = $products_id");
				
 $f = tep_db_fetch_array($q);
				
  return ($f['products_id']>0);
}

function check_video($video,$products_id)
{
 if ($video == "" || empty($video)) return true;//not save in database
 	
 $q = tep_db_query("select id from " .TABLE_PRODUCTS_VIDEOS. " where products_id = $products_id  and video = '".tep_db_prepare_input($video)."'");
				
 $f = tep_db_fetch_array($q);
				
  return ($f['id']>0);
}

function get_father_cat($cat_id)
{	
    if ($cat_id==0) return 0;
	
	$query = tep_db_query("SELECT parent_id from " . TABLE_CATEGORIES . " where categories_id= " .$cat_id);
				
	$m = tep_db_fetch_array($query);
								
	if (is_array($m)) { $current_parent_id = $m['parent_id']; } else $current_parent_id = 0;	
	
	return $current_parent_id;
}

function get_manu_id($manufac)
{
	$m_query = tep_db_query("select manufacturers_id from " . TABLE_MANUFACTURERS . " where manufacturers_name = '" . tep_db_prepare_input($manufac)."'");
				
	$manufacture = tep_db_fetch_array($m_query);
				
	if (is_array($manufacture)) { $manu_id = $manufacture['manufacturers_id']; }
	else $manu_id = 0;	
	
	return $manu_id;
}

function new_manu_id($manufacturers_name)
{
  $sql_data_array = array('manufacturers_name' => $manufacturers_name);

  $insert_sql_data = array('date_added' => 'now()');

  $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

  tep_db_perform(TABLE_MANUFACTURERS, $sql_data_array);
  $manufacturers_id = tep_db_insert_id();
  
  $languages = tep_get_languages();
  
  for ($i=0, $n = sizeof($languages); $i<$n; $i++) 
     {
          $language_id = $languages[$i]['id'];

          $sql_data_array = array('manufacturers_url' => '');

          $insert_sql_data = array('manufacturers_id' => $manufacturers_id,
                                     'languages_id' => $language_id);

          $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

          tep_db_perform(TABLE_MANUFACTURERS_INFO, $sql_data_array);
     }
	   
  return $manufacturers_id;
}

function get_category_id($category,$lang_id=1,$path)
{
	$query = tep_db_query("SELECT categories_id from " . TABLE_CATEGORIES_DESCRIPTION . 
	" where categories_name LIKE '" . tep_db_prepare_input($category)."' and categories_path LIKE '".tep_db_prepare_input($path)."'  and language_id = $lang_id");
		
	//echo "SELECT categories_id from " . TABLE_CATEGORIES_DESCRIPTION . " where categories_name LIKE '" . tep_db_prepare_input($category)."' and categories_path LIKE '".tep_db_prepare_input($path)."'  and language_id = $lang_id | ";
				
	$m = tep_db_fetch_array($query);
								
	if (is_array($m)) { $current_category_id = $m['categories_id']; }
	else $current_category_id = 0;	
	
	//echo " category_id = $current_category_id  <br>";
	
	return $current_category_id;
}
/*
function get_category_id($category,$lang_id=1)
{
	$query = tep_db_query("SELECT categories_id from " . TABLE_CATEGORIES_DESCRIPTION . 
	" where categories_name = '" . tep_db_prepare_input($category)."'  and language_id = $lang_id");
				
	$m = tep_db_fetch_array($query);
								
	if (is_array($m)) { $current_category_id = $m['categories_id']; }
	else $current_category_id = 0;	
	
	return $current_category_id;
}
*/
function new_category($current_category_id,$categories_name,$category_path)//parent_id'
{
 		$query = tep_db_query("SELECT MAX(sort_order) as max_order from " . TABLE_CATEGORIES);
				
		$m = tep_db_fetch_array($query);
		
		if (is_array($m)) { $max = (int)($m['max_order'])+1; }
		else $max = 0;			
	
        $sql_data_array = array('sort_order' => $max);
     
        $insert_sql_data = array('parent_id' => $current_category_id,'date_added' => 'now()');

        $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

        tep_db_perform(TABLE_CATEGORIES, $sql_data_array);

        $categories_id = tep_db_insert_id();

        $languages = tep_get_languages();
		
        for ($i=0, $n=sizeof($languages); $i<$n; $i++) {

            $language_id = $languages[$i]['id'];

            $sql_data_array = array('categories_name' => tep_db_prepare_input($categories_name));

            $insert_sql_data = array('categories_id' => $categories_id,
                                     'language_id' => $language_id,
									 'categories_path' => $category_path,
									 );

            $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

            tep_db_perform(TABLE_CATEGORIES_DESCRIPTION, $sql_data_array);         
        }
		
  return $categories_id;		
}
?>